import type { AxiosInstance, AxiosResponse, AxiosRequestConfig, AxiosRequestHeaders } from "axios";

export interface AxiosRequestConfig2 extends AxiosRequestConfig {
  headers?: AxiosRequestHeaders;
  tipSuccess?: boolean;
  tipError?: boolean;
  rawData?: boolean;
}

export type HttpConfig = {
  baseURL: string;
  commonHeaders: { [p: string]: string };
  postHeaders: { [p: string]: string };
  getHeaders: { [p: string]: string };
  requestInterceptors: ((conf: AxiosRequestConfig2) => AxiosRequestConfig2)[];
  responseInterceptors: ((res: AxiosResponse) => AxiosResponse)[];
};

export const setupAxios = (
  { baseURL, commonHeaders, postHeaders, getHeaders, requestInterceptors, responseInterceptors }: HttpConfig,
  axiosInstance: AxiosInstance
) => {
  axiosInstance.defaults.baseURL = baseURL;
  commonHeaders && (axiosInstance.defaults.headers.common = { ...axiosInstance.defaults.headers.common, ...commonHeaders });
  postHeaders && (axiosInstance.defaults.headers.post = { ...axiosInstance.defaults.headers.post, ...postHeaders });
  getHeaders && (axiosInstance.defaults.headers.get = { ...axiosInstance.defaults.headers.post, ...getHeaders });
  requestInterceptors.reverse();
  requestInterceptors.forEach((interceptor: any) => {
    axiosInstance.interceptors.request.use(interceptor as any, err => {
      throw err;
    });
  });
  responseInterceptors.forEach((interceptor: any) => {
    axiosInstance.interceptors.response.use(interceptor, err => {
      throw err;
    });
  });
};

// /**
//  * this.$get(APP.API_USER_NAME,{id:123}).then()
//  * this.$get(API_USER_NAME,{id:123},{tipError:false,tipSuccess:false,rawData:true,_id:'id'}).then()
//  *
//  * axios 完整配置 http://www.axios-js.com/zh-cn/docs/#%E8%AF%B7%E6%B1%82%E9%85%8D%E7%BD%AE
//  *
//  */
